package com.xiu.travel.security.service.impl;

import com.xiu.travel.constant.MessageConstant;
import com.xiu.travel.entity.UmsMember;
import com.xiu.travel.enums.RoleEnum;
import com.xiu.travel.exception.Asserts;
import com.xiu.travel.security.mapper.SysMenuMapper;
import com.xiu.travel.security.mapper.SysRoleMapper;
import com.xiu.travel.security.mapper.UmsMemberMapper;
import com.xiu.travel.security.pojo.SecurityUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author yingyingying
 * @date 2023/3/13 20:45
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UmsMemberMapper umsMemberMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        boolean isBack = username.contains("back_");
        UmsMember umsMember = umsMemberMapper.selectOne(new LambdaQueryWrapper<UmsMember>().eq(UmsMember::getUsername
                , isBack ? username.replaceFirst("back_", "") : username));
        //查询对应权限的消息
        if (Objects.isNull(umsMember)) {
            Asserts.fail(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        List<String> perms = Objects.requireNonNullElse(sysMenuMapper.selectPermsByUserId(umsMember.getId()), Collections.emptyList());
        List<String> roles = Objects.requireNonNullElse(sysRoleMapper.selectRoleByUserId(umsMember.getId()), Collections.emptyList());
        if (isBack && !CollectionUtils.containsAny(roles, Arrays.asList(RoleEnum.WAREHOUSE_KEEPER.getValue(),
                RoleEnum.STORE_MANAGER.getValue()
                , RoleEnum.ADMIN.getValue(), RoleEnum.SHOP_ASSISTANT.getValue()))) {
            Asserts.fail(MessageConstant.PERMISSION_DENIED);
        }
        //把数据封装返回
        return new SecurityUser(umsMember, perms, roles);

    }
}
